package com.nfcprogram.wifi;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

import android.util.Log;

import com.nfcprogram.handover.ContextAwareManager;

public class PingServerThread extends Thread {
	
		private static final String PING_SERVER_THREAD = "PingServerThread";
		private static final int ERROR_COUNT_MAX = 3;
		private static final int SUCCESS_COUNT_MAX = 3;
		private static final int SLEEPTIME = 10*1000;
		private static final int PING_PORT = 3333;
		private static final int TIMEOUT = 3*1000;
		private static final boolean V = true;
		private String ip = null;
		private int countError, countSuccess;
		private boolean keepAlive;
		private final WiFiService wiFiService;
		private final boolean urgent;

        public PingServerThread(WiFiService wiFiService, String ip) {
        	super(PING_SERVER_THREAD);
			this.wiFiService = wiFiService;
            this.ip = ip;
            countSuccess = countError = 0;
            keepAlive = true;
            urgent = false;
        }
        
        public PingServerThread(WiFiService wiFiService, String ip2, boolean urgent) {
        	super(PING_SERVER_THREAD);
			this.wiFiService = wiFiService;
			this.urgent = urgent;
            this.ip = ip2;
            countSuccess = countError = 0;
            keepAlive = true;
		}

		@Override
        public void run() {
        	if (V) Log.v(PING_SERVER_THREAD, "! PingServerThread started");
        	if(!urgent){
	        	try {
					Thread.sleep(3*SLEEPTIME);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
        	}
			while(keepAlive){
        		Socket socket = new Socket();
        		InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, PING_PORT);
        		try {
					socket.connect(inetSocketAddress,TIMEOUT);
					socket.close();
					updateCountersForSuccess();
					if (V) Log.v(PING_SERVER_THREAD, "! Server just pong");
					Thread.sleep(SLEEPTIME);
				} catch (SocketTimeoutException e) {
					updateCountersForError();
					if (V) Log.v(PING_SERVER_THREAD, "! Pong not received from Server");
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} 
        	}
        }

		private void updateCountersForError() {
			countError++;
			if(countError >= ERROR_COUNT_MAX){
				ContextAwareManager.getInstance().wifiDisconnected();
				countError = 0;
				countSuccess = 0;
			}
		}

		private void updateCountersForSuccess() {
			 countSuccess++;
			if(countSuccess >= SUCCESS_COUNT_MAX){
				ContextAwareManager.getInstance().wifiReconnected();
				countError = 0;
				countSuccess = 0;
			}
			if(!wiFiService.isClientConnected()){
				wiFiService.tryStart(ip);
			}
		}

		public void cancel() {
			keepAlive = false;
			this.interrupt();
		}
}